package com.yserp.project.erp.order.purchorder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yserp.common.exception.BusinessException;
import com.yserp.common.utils.StringUtils;
import com.yserp.common.utils.bean.BeanUtils;
import com.yserp.common.utils.mybatis.MybatisPlusUtil;
import com.yserp.common.utils.text.Convert;
import com.yserp.project.erp.bill.payment.domain.PaymentItem;
import com.yserp.project.erp.common.enums.CheckStatusEnums;
import com.yserp.project.erp.common.enums.OrderEnums;
import com.yserp.project.erp.common.enums.PayStatusEnums;
import com.yserp.project.erp.order.purchorder.domain.PurchOrder;
import com.yserp.project.erp.order.purchorder.domain.PurchOrderDto;
import com.yserp.project.erp.order.purchorder.domain.PurchOrderItem;
import com.yserp.project.erp.order.purchorder.domain.PurchOrderVo;
import com.yserp.project.erp.order.purchorder.mapper.PurchOrderMapper;
import com.yserp.project.erp.order.purchorder.service.IPurchOrderItemService;
import com.yserp.project.erp.order.purchorder.service.IPurchOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 采购订单Service业务层处理
 *
 * @author yserp
 * @date 2022-08-02
 */
@Service
public class PurchOrderServiceImpl extends ServiceImpl<PurchOrderMapper, PurchOrder> implements IPurchOrderService {
    @Resource
    private PurchOrderMapper purchOrderMapper;
    @Autowired
    private IPurchOrderItemService purchOrderItemService;

    /**
     * 查询采购订单
     *
     * @param id 采购订单主键
     * @return 采购订单
     */
    @Override
    public PurchOrderVo selectPurchOrderById(Long id) {

        PurchOrderVo vo = new PurchOrderVo();
        vo.setPurchOrder(purchOrderMapper.selectById(id));
        vo.setItems(purchOrderItemService.selectPurchOrderItemListByMainId(id));
        return vo;
    }

    /**
     * 查询采购订单列表
     *
     * @param purchOrder 采购订单
     * @return 采购订单
     */
    @Override
    public List<PurchOrder> selectPurchOrderList(PurchOrder purchOrder) {
        QueryWrapper<PurchOrder> query = new QueryWrapper<>();
        MybatisPlusUtil.notNullField(purchOrder,query);
        return purchOrderMapper.selectList(query);
    }

    /**
     * 新增采购订单
     *
     * @param purchOrderDto 采购订单
     * @return 结果
     */
    @Override
    public int insertPurchOrder(PurchOrderDto purchOrderDto) {
        List<PurchOrderItem> items = purchOrderDto.getItems();
        if (CollectionUtils.isEmpty(items)) {
            throw new BusinessException("子表不能为空");
        }
        //验证单号是否存在
        String orderNo = purchOrderDto.getOrderNo();
        if(StringUtils.isBlank(orderNo)){
            throw new BusinessException("单号不存在");
        }
        Integer count = purchOrderMapper.selectCount(new QueryWrapper<PurchOrder>().eq("order_no", orderNo));
        if(count>0){
            //处理单号，并重新插入缓存
            Integer number = purchOrderMapper.selectCount(new QueryWrapper<PurchOrder>().like("order_no", orderNo.substring(0,orderNo.length()-3)));
            OrderEnums.putCacheOrderNo(orderNo,number);
            throw new BusinessException("单号已存在，请重新下单");
        }else{
            OrderEnums.putCacheOrderNo(orderNo);
        }
        //插入主表
        PurchOrder purchOrder = new PurchOrder();
        BeanUtils.copyBeanProp(purchOrder, purchOrderDto);
        int i = purchOrderMapper.insert(purchOrder);
        //批量插入子表
        items.stream().forEach(item-> item.setMainId(purchOrder.getId()));
        purchOrderItemService.saveBatch(items);
        return i;
    }

    /**
     * 修改采购订单
     *
     * @param purchOrderDto 采购订单
     * @return 结果
     */
    @Override
    public int updatePurchOrder(PurchOrderDto purchOrderDto) {
        List<PurchOrderItem> items = purchOrderDto.getItems();
        if(CollectionUtils.isEmpty(items)){
            throw new BusinessException("子表不能为空");
        }
        //修改主表
        PurchOrder purchOrder = new PurchOrder();
        BeanUtils.copyBeanProp(purchOrder, purchOrderDto);
        int i = purchOrderMapper.updateById(purchOrder);
        //子表
        Long mainId = purchOrder.getId();
        //获取子表
        List<PurchOrderItem> purchOrderItems = purchOrderItemService.selectPurchOrderItemListByMainId(mainId);
        if(!CollectionUtils.isEmpty(purchOrderItems)) {
            List<Long> oldIds = purchOrderItems.stream().map(PurchOrderItem::getId).collect(Collectors.toList());
            List<Long> newIds = items.stream().map(PurchOrderItem::getId).collect(Collectors.toList());
            oldIds.removeAll(newIds);
            if (!CollectionUtils.isEmpty(oldIds)) {
                purchOrderItemService.removeByIds(oldIds);
            }
        }
        for (PurchOrderItem item : items) {
            item.setMainId(mainId);
            purchOrderItemService.saveOrUpdate(item);
        }
        return i;
    }

    /**
     * 批量删除采购订单
     *
     * @param ids 需要删除的采购订单主键
     * @return 结果
     */
    @Override
    public int deletePurchOrderByIds(String ids) {
        int result = 0;
        Long[] mainIds = Convert.toLongArray(ids);
        for (Long id : mainIds ) {
            result =this.deletePurchOrderById(id);
            if(result <= 0){
                break;
            }
        }
        return result;
    }

    /**
     * 删除采购订单信息
     *
     * @param id 采购订单主键
     * @return 结果
     */
    @Override
    public int deletePurchOrderById(Long id) {
        int result = 0;
        //更新主表
        int i=purchOrderMapper.deleteById(id);
        //查询子表信息
        List<PurchOrderItem> items = purchOrderItemService.selectPurchOrderItemListByMainId(id);
        if(!CollectionUtils.isEmpty(items)) {
            List<Long> itemIds = items.stream().map(PurchOrderItem::getId).collect(Collectors.toList());
            boolean b = purchOrderItemService.removeByIds(itemIds);
            if (i > 0 && b) {
                result = 1;
            }
        }
        return result;
    }

    @Override
    public int auditPurchOrderByIds(String ids) {
        int result = 1;
        Long[] mainIds = Convert.toLongArray(ids);
        PurchOrder purchOrder=null;
        List<PurchOrder> purchOrders =new ArrayList<>();
        for (Long id : mainIds ) {
            purchOrder = purchOrderMapper.selectById(id);
            //如果审核通过，无需再次审核
            if(CheckStatusEnums.OK_CHECK.getCode().equals(purchOrder.getOrderStatus())){
                continue;
            }
            purchOrder.setOrderStatus(CheckStatusEnums.OK_CHECK.getCode());
            purchOrders.add(purchOrder);
        }
        if(purchOrders.size()>0){
            this.updateBatchById(purchOrders);
        }

        return result;
    }

    @Override
    public List<PaymentItem> selectPurchOrderListBySupplierId(Long supplierId) {
        List<PaymentItem> mapList = new ArrayList<>();
        //查询数据(单独查询)
        QueryWrapper<PurchOrder> queryWrapper = new QueryWrapper<PurchOrder>()
                .eq("supplier_id", supplierId)
                .eq("order_status", CheckStatusEnums.OK_CHECK.getCode())
                .ne("pay_status", PayStatusEnums.OK_PAYMENT.getCode());
        List<PurchOrder> purchOrders = purchOrderMapper.selectList(queryWrapper);
        if(!CollectionUtils.isEmpty(purchOrders)) {
            for (PurchOrder order : purchOrders) {
                PaymentItem paymentItem = new PaymentItem();
                BigDecimal noPayAmount = order.getAmounts().subtract(order.getPayAmounts());
                paymentItem.setPurchId(order.getId());
                paymentItem.setPurchCode(order.getOrderNo());
                paymentItem.setNoPayAmount(noPayAmount);
                paymentItem.setRemark("");
                mapList.add(paymentItem);
            }
        }
        return mapList;
    }
}
